from django.db import models
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.core.validators import MinValueValidator, RegexValidator


# 校验价格不能为负数
def validate_price(value):
    if value < 0:
        raise ValidationError('Price cannot be negative.')


# 用户表
class User(models.Model):
    # 用户 ID（Django 自动生成）
    id = models.AutoField(primary_key=True)

    # 用户名
    username = models.CharField(
        max_length=50,
        unique=True,
        verbose_name="用户名",
        help_text="默认为微信昵称"
    )

    # 头像 ID（关联图像数据库）
    avatar_id = models.ForeignKey(
        'Image',  # 关联到 Image 模型
        on_delete=models.SET_NULL,  # 当 Image 被删除时，将该字段设为 NULL
        null=True,  # 允许该字段为空
        blank=True,  # 允许该字段为空
        verbose_name="头像 ID",
        help_text="关联图像数据库中的图像编号"
    )

    # 微信 OpenID
    openid = models.CharField(
        max_length=100,
        unique=True,
        verbose_name="微信 OpenID",
        help_text="微信用户的唯一标识"
    )

    # 手机号
    phonenumber = models.CharField(
        max_length=15,
        verbose_name="手机号",
        help_text="用户的手机号",
        validators=[
            RegexValidator(
                regex=r'^\+?1?\d{9,15}$',
                message="手机号格式不正确"
            )
        ],
        null=True,
        blank=True
    )

    # 创建时间
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="创建时间",
        help_text="用户的注册时间"
    )

    # 会员剩余时间（单位：天）
    membertime = models.IntegerField(
        verbose_name="会员剩余时间",
        help_text="会员剩余时间，单位为小时",
        default=0,
        validators=[
            MinValueValidator(0, message="会员剩余时间不能小于 0")
        ]
    )

    def __str__(self):
        return self.username

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"


# 产品表
class Product(models.Model):
    id = models.AutoField(primary_key=True)

    subid = models.IntegerField(
        verbose_name="Product Type",
        help_text="Product type identifier"
    )

    productname = models.CharField(
        max_length=255,
        verbose_name="Product Name",
        help_text="Product name"
    )

    description = models.TextField(
        verbose_name="Product Description",
        help_text="Product description"
    )

    price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        validators=[validate_price],
        verbose_name="Price",
        help_text="Product price"
    )

    total_use = models.IntegerField(
        verbose_name="Total Uses",
        default=0,
        help_text="Total times this product has been used"
    )

    is_active = models.BooleanField(
        default=True,
        verbose_name="Is Active",
        help_text="Whether the product is still available for sale"
    )

    created_at = models.DateTimeField(
        default=timezone.now,
        verbose_name="Creation Time",
        help_text="Time when the product was created"
    )

    covar_id = models.ForeignKey(
        'Image',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="product_cover",
        verbose_name="Cover Image",
        help_text="The cover image associated with the product"
    )

    en_description = models.TextField(
        verbose_name="English Description",
        help_text="English description of the product"
    )

    member_price = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        validators=[validate_price],
        verbose_name="Member Price",
        help_text="Price for members"
    )

    maxtimes = models.IntegerField(
        verbose_name="Max Purchase Times",
        default=1,
        help_text="Maximum purchase times per account"
    )

    location = models.CharField(
        max_length=255,
        verbose_name="Product Location",
        blank=True,
        null=True
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="Updated Time",
        help_text="Time when the product was last updated"
    )
    def __str__(self):
        return self.productname

    class Meta:
        verbose_name = 'Product'
        verbose_name_plural = 'Products'
        ordering = ['-updated_at']  # 默认按更新时间倒序排列


# 图片表
class Image(models.Model):
    id = models.AutoField(primary_key=True)

    name = models.CharField(
        max_length=255,
        verbose_name="Image Name",
        help_text="Name of the image"
    )

    url = models.URLField(
        verbose_name="Image URL",
        help_text="URL of the image"
    )

    type = models.CharField(
        max_length=100,
        verbose_name="Image Type",
        help_text="The type/category of the image"
    )

    created_at = models.DateTimeField(
        default=timezone.now,
        verbose_name="Creation Time",
        help_text="Time when the image was created"
    )

    description = models.TextField(
        blank=True,
        null=True,
        verbose_name="Description",
        help_text="Description of the image"
    )

    format = models.CharField(
        max_length=50,
        verbose_name="Image Format",
        help_text="Format of the image (e.g., JPG, PNG)"
    )

    def __str__(self):
        return str(self.id)

    class Meta:
        verbose_name = 'Image'
        verbose_name_plural = 'Images'


class Coach(models.Model):
    # 自动生成的主键
    id = models.AutoField(primary_key=True, verbose_name="教练ID")

    name = models.CharField(
        max_length=100,
        verbose_name="姓名",
        help_text="教练的全名"
    )

    birth_date = models.DateField(
        verbose_name="出生日期",
        null=True,
        blank=True
    )

    description = models.TextField(
        verbose_name="个人描述",
        blank=True,
        null=True,
        help_text="教练的详细介绍"
    )

    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message="电话号码格式必须为: '+999999999'"
    )
    phone_number = models.CharField(
        validators=[phone_regex],
        max_length=17,
        blank=True,
        verbose_name="电话号码"
    )

    wechat_id = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        verbose_name="微信号"
    )

    cover_image = models.ForeignKey(
        'Image',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="封面照片",
        related_name='coach_cover_images'
    )

    tags = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name="标签",
        help_text="用逗号分隔的标签"
    )

    en_description = models.TextField(
        verbose_name="英文描述",
        blank=True,
        null=True,
        help_text="教练的英文介绍"
    )

    created_at = models.DateTimeField(
        default=timezone.now,
        verbose_name="创建时间"
    )

    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="更新时间"
    )

    def get_tags_list(self):
        """将标签字符串转换为列表"""
        return [tag.strip() for tag in self.tags.split(',')] if self.tags else []

    def __str__(self):
        return f"{self.name} (ID: {self.id})"

        verbose_name = '教练'
        verbose_name_plural = '教练列表'
        ordering = ['-created_at']